import os
import sys
import glob

def check_required_files():
    script_dir = os.path.dirname(os.path.abspath(__file__))
    required_files = [
        'hvigorfile.ts',
        'build-profile.json5',
        'hvigor/hvigor-config.json5',
        'entry/src/',
        'entry/build-profile.json5',
        'entry/hvigorfile.ts'
    ]
    missing_files = []

    # 检查 hvigor 目录下是否有cangjie-build-support-*.tgz文件
    hvigor_dir = os.path.join(script_dir, 'hvigor')
    has_tgz = False
    if os.path.isdir(hvigor_dir):
        tgz_files = glob.glob(os.path.join(hvigor_dir, 'cangjie-build-support-*.tgz'))
        if tgz_files:
            has_tgz = True
    if not has_tgz:
        missing_files.append('hvigor/cangjie-build-support-*.tgz')
    for path in required_files:
        full_path = os.path.join(script_dir, path)
        if os.path.isdir(full_path):
            if not os.path.exists(full_path):
                missing_files.append(path)
        else:
            if not os.path.isfile(full_path):
                missing_files.append(path)
    missing_files

def main():
    missing_files = check_required_files()

    if missing_files:
        print("缺失cangjie工程所需的全部配置文件")
        for f in missing_files:
            print(f"缺失{f}文件")
     
    choice = input("升级不可逆，不再支持低版本!!!是否升级cangjie工程：确定(输入yes)/退出(输入0)：").strip().lower()
    if choice not in ['yes', '0']:
        print("无效的选择，退出。")
        return
    if choice == '0':
        return
    
    # 替换build-profile.json5中的 cangjieOptions字段
    def replace_cangjieOptions_in_file(file_path):
        # 直接替换文本
        try:
            # 读取文件内容
            with open(file_path, 'r', encoding = 'utf-8') as f:
                content = f.read()
            # 替换
            modified_content = content.replace('cangjieOptions', 'cangjie')
            # 只有修改文件之后才重新写回文件并提示
            if modified_content != content:
                with open(file_path, 'w', encoding = 'utf-8') as f:
                    f.write(modified_content)
                print(f"已修改文件：{file_path}, 将 cangjieOptions 替换为 cangjie")
        except Exception as e:
            print(f"处理 {file_path} 时出错：{e}")
    
    # 替换hvigorfile.ts中的字段
    def replace_hvigorfile_content(file_path):
        try:
            # 读取文件内容
            with open(file_path, 'r', encoding = 'utf-8') as f:
                content = f.read()
            # 替换
            new_content = content.replace('@ohos/cangjie-build-support', '@ohos/hvigor-ohos-plugin')
            # 只有修改文件之后才重新写回文件并提示
            if new_content != content:
                with open(file_path, 'w', encoding = 'utf-8') as f:
                    f.write(new_content)
                print(f"已修改文件：{file_path}, 将 @ohos/cangjie-build-support 替换为 @ohos/hvigor-ohos-plugin")
        except Exception as e:
            print(f"处理 {file_path} 时出错：{e}")

    # 删除hvigor-config.json5中的cangjie-build-support依赖行
    def remove_cangjie_dependency(file_path):
        try:
            # 读取文件内容
            with open(file_path, 'r', encoding = 'utf-8') as f:
                lines = f.readlines()
            # 删除
            modified_lines = []
            for line in lines:
                if '@ohos/cangjie-build-support'not in line:
                    modified_lines.append(line)
            # 只有修改文件之后才重新写回文件并提示
            if modified_lines != lines:
                with open(file_path, 'w', encoding = 'utf-8') as f:
                    f.writelines(modified_lines)
                print(f"已修改文件：{file_path}, 删除了依赖项 @ohos/cangjie-build-support")
        except Exception as e:
            print(f"处理 {file_path} 时出错：{e}")

    script_dir = os.path.dirname(os.path.abspath(__file__))
    for root, dirs, files in os.walk(script_dir):
        # 跳过oh_modules目录
        if 'oh_modules' in dirs:
            dirs.remove('oh_modules')
        for file in files:
            if file == 'build-profile.json5':
                full_path = os.path.join(root, file)
                try:
                    replace_cangjieOptions_in_file(full_path)
                except Exception as e:
                    print(f"处理 {full_path} 时出错：{e}")
            elif file == 'hvigorfile.ts':
                full_path = os.path.join(root, file)
                try:
                    replace_hvigorfile_content(full_path)
                except Exception as e:
                    print(f"处理 {full_path} 时出错：{e}") 
            elif file == 'hvigor-config.json5':
                full_path = os.path.join(root, file)
                try:
                    remove_cangjie_dependency(full_path)
                except Exception as e:
                    print(f"处理 {full_path} 时出错：{e}") 

    # 删除hvigor目录下的cangjie-build-support-*.tgz
    hvigor_dir = os.path.join(script_dir, 'hvigor')
    if os.path.isdir(hvigor_dir):
        tgz_files = glob.glob(os.path.join(hvigor_dir, 'cangjie-build-support-*.tgz'))
        for tgz_file in tgz_files:
            try:
                os.remove(tgz_file)
                print(f"已删除文件：{tgz_file}")
            except Exception as e:
                print(f"删除文件{tgz_file}时出错：{e}")
    print("工程升级完成，请 Sync And Refresh Project")

if __name__ == "__main__":
    main()
